package twitmasturbation.servlet;

import twitmasturbation.Constants;
import twitmasturbation.jdo.PMF;
import twitmasturbation.jdo.table.HistoryTbl;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.List;



public class SigninServlet extends HttpServlet {
    private static final long serialVersionUID = -6205814293093350242L;

	/** {@link org.apache.commons.logging.Log} オブジェクト。 */
	protected static final Log LOG = LogFactory.getLog(SigninServlet.class);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Twitter twitter = new TwitterFactory().getInstance();
        request.getSession().setAttribute("twitter", twitter);
        try {

// SigninとこでSpermSumとか取るのマチガイ
//        	//TODO:データアクセスのところは移植性を考えてDAOとして分離したほうがいい
//            // 累計何回目のオナニーかをHistoryTblから調べる
//            PersistenceManager pmGet = PMF.get().getPersistenceManager();
//
//            String query = "select from " + HistoryTbl.class.getName();
//            System.out.println("[SigninServlet] 実行クエリ:" + query);
//            List<HistoryTbl> historys = (List<HistoryTbl>) pmGet.newQuery(query).execute();
//
//            int spermSum = Constants.SPERM * historys.size();
//            request.getSession().setAttribute("spermSum", spermSum);
//            request.getSession().setAttribute("spermConst", Constants.SPERM);


            StringBuffer callbackURL = request.getRequestURL();
            int index = callbackURL.lastIndexOf("/");
            callbackURL.replace(index, callbackURL.length(), "").append("/callback");

            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());

            LOG.info("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            throw new ServletException(e);
        }

    }
}
